package com.snap.vseries.ui;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;

import com.snap.vseries.R;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.base.OnDebounceClickListener;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.manager.ConfigManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.ui.widget.TextButton;
import com.snap.vseries.utils.ToastUtils;

import org.litepal.crud.callback.FindMultiCallback;

import java.io.File;
import java.util.List;

import butterknife.BindView;

public class LoginActivity extends BaseActivity {
    private static final int REQUEST_PERMISSION = 10;
    private static String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @BindView(R.id.login_btn)
    TextButton loginBtn;
    private boolean gotNecessaryPermission;

    @Override
    protected int layoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //申请权限
        // TODO: 2021/1/12 添加
//        Logger.e("本次开机时间为:" + sdf.format(date) + ",系统版本为" + BuildConfig.VERSION_NAME);
        ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION);
        initView();
        checkUpdate();
//        traverseFolder(LoginActivity.this, Environment.getExternalStorageDirectory().getPath() + AppConfig.EXPERIMENT_DIRECTORY)
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ToastUtils.get().showText("获取权限失败,部分功能可能无法正常使用！");
            } else {
                gotNecessaryPermission = true;
            }
        }
    }

    private void initView() {
        loginBtn.setOnClickListener(new OnDebounceClickListener() {
            @Override
            public void doClick(View v) {
                if (gotNecessaryPermission) {
                    ConfigManager.getInstance().init();
                    HomeActivity.startActivity(LoginActivity.this);
                    finish();
                } else {
                    ActivityCompat.requestPermissions(LoginActivity.this, permissions, REQUEST_PERMISSION);
                }
            }
        });
    }

    private void checkUpdate() {
//        SharedPreferences sp = getSharedPreferences("mole" + BuildConfig.VERSION_NAME, 0);
//        boolean firstRun = sp.getBoolean("first_run", true);
//        if (firstRun) {
//            sp.edit().putBoolean("first_run", false).apply();
//        } else {
//            ApkUtils.checkUpdate(this);
//        }
    }


    /**
     * 开发中的需求，发布时未必使用
     * 将指定目录中的文件添加至 历史数据列表中
     */
    private void traverseFolder(Context context, String path) {
        File file = new File(path);
        if (!file.exists()) return;
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            DBManager.get().getAllExp(new FindMultiCallback<ExpEntity>() {
                @Override
                public void onFinish(List<ExpEntity> list) {
                    List<ExpEntity> experimentList = list;
                    for (File file1 : files) {
                        boolean isExit = false;
                        for (ExpEntity experiment : experimentList) {
                            if (TextUtils.equals(experiment.getName() + ".exp", file1.getName())) {
                                isExit = true;
                            }
                        }
                        if (!isExit) {
                            String fileName = file1.getName().split("\\.")[0];
                            DBManager.get().saveExp(new ExpEntity(), isSuccess -> {
                            });
                        }
                    }
                }
            });
        }
    }
}
